import plugin from "../../../lib/plugins/plugin.js"
import {segment} from "oicq";
import Yaml from '../Yaml/Yaml.js'
import _ from "underscore"

let rootPath = process.cwd()
let pluginPath = rootPath + '/plugins/fisticuffs-plugin/config/'
let appConfigPath = pluginPath + 'application.yaml'
let normalTalkConfigPath = pluginPath + 'normalTalk.yaml'
let kawaiiTalkConfigPath = pluginPath + 'kawaiiTalk.yaml'
let dirtyTalkConfigPath = pluginPath + 'dirtyTalk.yaml'

const checkAbsoluteMasterFalse = async function (e, absoluteMaster) {
    if (absoluteMaster === null) {
        let msg = '请先发送【设置绝对权限】再使用功能！'
        if (e.isGroup) {
            e.reply([segment.at(e.user_id), msg])
        } else {
            e.reply(msg)
        }
        return false;
    }
    return true;
}

/**
 * 获取骂人类型
 * @param e
 * @param type  1判断对话 2判断配置
 * @param config
 * @returns {Promise<boolean>}
 */
const getAbuseType = async function (type, e = {}, config = {}) {

    let configPath = false

    if (
        (type === 1 && e.msg.includes('可爱')) ||
        (type === 2 && config.abuseType === 1)
    ) {
        configPath = kawaiiTalkConfigPath
    } else if (
        (type === 1 && e.msg.includes('正常')) ||
        (type === 2 && config.abuseType === 2)
    ) {
        configPath = normalTalkConfigPath
    } else if (
        (type === 1 && e.msg.includes('暴躁')) ||
        (type === 2 && config.abuseType === 3)
    ) {
        configPath = dirtyTalkConfigPath
    }
    return configPath
}

export class curse extends plugin {
    constructor() {
        super({
            name: '骂人骂人',
            dsc : '彻底疯狂',
            /** https://oicqjs.github.io/oicq/#events */
            event   : 'message',
            priority: 4999,
            rule    : [
                {
                    /** 命令正则匹配 */
                    reg: '^(可爱|正常|暴躁)词条列表$',
                    /** 执行方法 */
                    fnc: 'sentenceList',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^(写入|删除)(可爱|正常|暴躁)词条(.*)$',
                    /** 执行方法 */
                    fnc: 'storeSentence',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^变(可爱|正常|暴躁)$',
                    /** 执行方法 */
                    fnc: 'setAbuseType',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^彻底疯狂|低调一点$',
                    /** 执行方法 */
                    fnc: 'setAbuseStatus',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^(.*?)$',
                    /** 执行方法 */
                    fnc: 'abuse'
                }
            ]
        })
    }

    // (可爱|正常|暴躁)词条列表
    async sentenceList(e) {

        // 群聊禁用，词汇量较少就别献丑了，或者狠活儿不要别人剽窃了
        if (e.isGroup) {
            return false
        }

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let configPath = await getAbuseType(1, e)
        if (!configPath) {
            return configPath
        }

        let sentenceList = await Yaml.read(configPath)

        if (_.isEmpty(sentenceList) || !_.isArray(sentenceList)) {
            e.reply('词条还没有词条可以用呢~请用指令【写入词条+词条】新增词条~')
            return false;
        }

        let nickname = Bot.nickname
        if (e.isGroup) {
            let info = await Bot.getGroupMemberInfo(e.group_id, Bot.uin)
            nickname = info.card ?? info.nickname
        }
        let userInfo = {user_id: Bot.uin, nickname}
        let replyMessage = [{...userInfo, message: '词条列表\n可使用指令【删除词条+(序号)】删除掉对应的词条'}]

        let msg = ''
        for (let i = 0; i < sentenceList.length; i++) {
            let item = sentenceList[i]
            msg += `${i + 1}.${item}\n`
        }
        replyMessage.push({...userInfo, message: msg})

        if (e.isGroup) {
            replyMessage = await e.group.makeForwardMsg(replyMessage)
        } else {
            replyMessage = await e.friend.makeForwardMsg(replyMessage)
        }
        replyMessage.data = replyMessage.data
            .replace(/\n/g, '')
            .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
            .replace(/___+/, `<title>词条列表</title>`)

        await e.reply(replyMessage);

        return false;
    }

    // 写入 词条/删除 可爱/正常/暴躁 词条
    async storeSentence(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let configPath = await getAbuseType(1, e)
        if (!configPath) {
            return configPath
        }

        let sentenceList = await Yaml.read(configPath)
        if (!_.isArray(sentenceList)) {
            sentenceList = []
        }

        if (e.msg.includes('写入词条')) {
            let sentence = e.msg.replace(/写入词条/g, '').trim()
            if (!sentence) {
                e.reply('词条呢？词条呢？词条呢？');
                return false
            }

            sentenceList.push(sentence)
            Yaml.write(configPath, sentenceList)

            e.reply(`【${sentence}】成功添加进词条可使用指令【词条列表】查看~`);

        } else if (e.msg.includes('删除词条')) {
            let position = e.msg.match(/([1-9]\d*)|([1-9]\d*-[1-9]\d*)/g)

            if (!_.isArray(position) || position.length === 0 || position.length > 2) {
                e.reply('序号有问题~');
                return false
            }

            let index = parseInt(position[0]) - 1
            let length

            if (position.length === 1) {
                length = 1
            } else {
                length = parseInt(position[1]) - index
            }

            if (index < 0 || length <= 0) {
                e.reply('序号有问题~');
                return false
            }

            let oldLength = sentenceList.length
            sentenceList.splice(index, length)
            Yaml.write(configPath, sentenceList)
            let newLength = sentenceList.length

            e.reply(`成功删除${oldLength - newLength}个词条，可使用指令【词条列表】查看~`)
        }

        return false;
    }

    // 变(可爱|正常|暴躁)
    async setAbuseType(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        if (e.msg.trim() === '变可爱') {
            appConfig.abuseType = 1
            e.reply('★KIRA☆');
        } else if (e.msg.trim() === '变正常') {
            appConfig.abuseType = 2
            e.reply('好的~');
        } else if (e.msg.trim() === '变暴躁') {
            appConfig.abuseType = 3
            e.reply('知道了，滚吧');
        } else {
            return false
        }

        Yaml.write(appConfigPath, appConfig)

        return false
    }

    // 彻底疯狂/低调一点
    async setAbuseStatus(e) {

        if (!e.isGroup) {
            e.reply('你自己疯吧..')
            return false
        }

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster
        let crazyGroup = appConfig.crazyGroup

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        if (e.msg.includes('彻底疯狂')) {
            if (!crazyGroup.includes(e.group_id)) {
                crazyGroup.push(e.group_id)
            }
            e.reply('啊啊啊啊！彻底~~~疯狂！！！！');
        } else if (e.msg.includes('低调一点')) {
            if (crazyGroup.includes(e.group_id)) {
                crazyGroup = _.difference(crazyGroup, [e.group_id])
            }
            e.reply('喵~');
        }

        appConfig.crazyGroup = crazyGroup
        Yaml.write(appConfigPath, appConfig)

        return false
    }

    // 开骂
    async abuse(e) {

        // 私聊禁用
        if (!e.isGroup) {
            return false
        }

        let appConfig = await Yaml.read(appConfigPath)
        let enableGroup = appConfig.enableGroup
        let crazyGroup = appConfig.crazyGroup

        // 未启用的群禁用
        if (!enableGroup.includes(e.group_id)) {
            return false;
        }

        // 没被@ 且 该群不是疯狂模式 禁用
        if (!e.atBot && !crazyGroup.includes(e.group_id)) {
            return false;
        }

        let configPath = await getAbuseType(2, {}, appConfig)
        if (!configPath) {
            return configPath
        }

        let sentenceList = await Yaml.read(configPath)
        // 没词儿禁用
        if (_.isEmpty(sentenceList)) {
            return false;
        }

        e.reply([segment.at(e.user_id), sentenceList[Math.ceil(Math.random() * sentenceList.length) - 1]])

        return false;
    }
}
